package org.jaronsource.framework.plugins.easyui;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class EasyUIFilter implements Filter {

	@Override
	public void destroy() {}

	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(	ServletRequest request,
							ServletResponse response,
							FilterChain chain )	throws IOException,
												ServletException {

		HttpServletRequest httpServletRequset = (HttpServletRequest) request;
		HashMap<String, String[]> m = new HashMap<String, String[]>( request.getParameterMap() );
		ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper( httpServletRequset, m );
		String[] page = m.get( "page" );
		String[] rows = m.get( "rows" );
		String[] sort = m.get( "sort" );
		String[] order = m.get( "order" );

		m.put( "pageNo", page );
		m.put( "pageSize", rows );
		
		if (sort != null && sort.length > 0 && order != null && order.length > 0) {
			m.put( "order", new String[] { sort[0] + "_" + order[0] } );
		}

		chain.doFilter( parameterRequestWrapper, response );

	}

	@Override
	public void init( FilterConfig config ) throws ServletException {}

}
